﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace NotaManager
{
    public class Remember11Manager : IRemember11Manager
    {
        private const int PROCESS_WM_READ = 0x0010;

        private byte[] _buf = new byte[1];
        private List<byte> _allBytes = new List<byte>();


        [DllImport("kernel32.dll")]
        public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);

        [DllImport("kernel32.dll")]
        public static extern bool ReadProcessMemory(int hProcess,
          int lpBaseAddress, byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesRead);





        public string GetCurrentText(string processName, bool russian = false)
        {
            var processes = Process.GetProcessesByName(processName);
            if (processes.Length == 0)
	        {
                return null;
	        }

            var hwd = OpenProcess(PROCESS_WM_READ, false, processes[0].Id);

            int bytesRead = 0;
            int startAdress = 0x00E80F60;
            while (true)
            {
                ReadProcessMemory((int)hwd, startAdress, _buf, 1, ref bytesRead);

                if (_buf[0] == 0x00 || _allBytes.Count > 10 * 1000)
                {
                    break;
                }

                _allBytes.Add(_buf[0]);
                startAdress++;
            }

            var res = _allBytes.ToArray();
            string resultString = null;

            if (russian)
	        {
                resultString = res.ConvertToRus();
	        }
            else
            {
                resultString = res.ConvertToEng();
            }
           
            _allBytes.Clear();

            return resultString;
        }
    }
}
